#! /usr/bin/env python
# -*- coding: utf-8 -*-

import pymysql
from conf.base_conf import BaseConf


def get_query_count(sql_query: str):
    """
    通过自定义的sql语句从mysql数据库查询结果
    :param sql_query: 自定义sql语句，如：SELECT count(*) FROM hgyq_emergency.dual_m_imei where is_deleted = 0;
    :return:
    """
    # 把拼装sql里面的\t和\n替换成空格，不能直接删除（直接删除可能会导致两个关键字连在一起导致sql执行报错）
    sql_query = sql_query.replace('\n', ' ').replace('\t', ' ')
    try:
        # 建立数据库连接
        connection = pymysql.connect(
            host=BaseConf.MYSQL_HOST,
            user=BaseConf.MYSQL_USER,
            password=BaseConf.MYSQL_PASSWORD,
            port=BaseConf.MYSQL_PORT,
        )

        with connection:
            with connection.cursor() as cursor:
                # 执行 SQL 查询
                cursor.execute(sql_query)
                # 注意：这里只获取了一条数据
                res = cursor.fetchone()
                return res[0]
    except Exception as e:
        print(e)
        # 查询错误，返回-1
        return -1
